package com.sinosoft.vaccinetoai.server.configure;

import cn.hutool.json.JSONObject;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

import static org.apache.tomcat.jni.Socket.pool;

/**
 * OkHttp配置
 * @author xzh
 * @date 2022-10-24 12:49
 * @since 1.0.0
 */
@Configuration
public class OkHttpConfig {

    /**
     * 基于OkHttp3配置RestTemplate
     * @return
     */
    @Bean
    public RestTemplate restTemplate() {
        OkHttpClient httpClient = okHttpClient();
        OkHttp3ClientHttpRequestFactory factory = new OkHttp3ClientHttpRequestFactory(httpClient);
        RestTemplate restTemplate = new RestTemplate(factory);
        // 可以添加消息转换
        //restTemplate.setMessageConverters(...);
        // 可以增加拦截器
        //restTemplate.setInterceptors(...);
        return restTemplate;
    }

    @Bean
    public OkHttpClient okHttpClient() {
        return new OkHttpClient.Builder()
                //.sslSocketFactory(sslSocketFactory(), x509TrustManager())
                .retryOnConnectionFailure(false)
                .connectionPool(new ConnectionPool(200, 5, TimeUnit.MINUTES))
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30,TimeUnit.SECONDS)
                .build();
    }

    public static void main(String[] args) {
        OkHttpClient httpClient = new OkHttpClient.Builder()
                //.sslSocketFactory(sslSocketFactory(), x509TrustManager())
                .retryOnConnectionFailure(false)
                .connectionPool(new ConnectionPool(200, 5, TimeUnit.MINUTES))
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30,TimeUnit.SECONDS)
                .build();
        OkHttp3ClientHttpRequestFactory factory = new OkHttp3ClientHttpRequestFactory(httpClient);
        RestTemplate restTemplate = new RestTemplate(factory);

        JSONObject jsonObject = new JSONObject();
        jsonObject.set("prompt","老虎");
//        jsonObject.set("size",io.getSize());
//        jsonObject.set("n",io.getNum());
//        jsonObject.set("response_format",io.getFormat());
        ResponseEntity<JSONObject> entity = restTemplate.postForEntity("https://vaccinetoai-api.sinosoft.com/chatApi/api/img/create",jsonObject,JSONObject.class);

        System.out.println(entity.getBody().toString());
    }
}
